<template>
  <div class="avatar-test">
    <h2>头像上传测试</h2>
    
    <div class="test-section">
      <h3>当前头像</h3>
      <el-avatar 
        :src="avatarUrlComputed" 
        :size="100"
        @error="onAvatarError"
      />
    </div>
    
    <div class="test-section">
      <h3>上传新头像</h3>
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleFileChange"
        accept="image/*"
        class="avatar-uploader"
      >
        <el-button type="primary">选择图片</el-button>
      </el-upload>
      
      <div v-if="previewUrl" class="preview-section">
        <h4>预览</h4>
        <img :src="previewUrl" alt="预览" style="max-width: 200px; max-height: 200px;" />
        <div class="preview-actions">
          <el-button type="success" @click="uploadAvatar" :loading="uploading">
            确认上传
          </el-button>
          <el-button @click="cancelUpload">取消</el-button>
        </div>
      </div>
    </div>
    
    <div class="test-section">
      <h3>测试信息</h3>
      <p>当前头像URL: {{ doctorInfo.avatar || '无' }}</p>
      <p>计算后的URL: {{ avatarUrlComputed }}</p>
      <p>文件大小限制: 2MB</p>
      <p>支持格式: JPG, PNG, GIF</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadAvatar } from '../api/upload'
import { getAvatarUrl, validateAvatarFile, createAvatarPreview, base64ToFile } from '../utils/avatarUtils'

// 响应式数据
const doctorInfo = ref({})
const previewUrl = ref('')
const uploading = ref(false)
const uploadRef = ref()

// 计算属性 - 头像URL
const avatarUrlComputed = computed(() => {
  return getAvatarUrl(doctorInfo.value.avatar)
})

// 头像加载错误处理
const onAvatarError = () => {
  console.log('头像加载失败，使用默认头像')
}

// 文件选择处理
const handleFileChange = (file) => {
  console.log('选择的文件:', file)
  
  // 验证文件
  const validation = validateAvatarFile(file.raw)
  if (!validation.valid) {
    ElMessage.error(validation.message)
    return
  }
  
  // 创建预览
  createAvatarPreview(file.raw, (url) => {
    previewUrl.value = url
  })
}

// 上传头像
const uploadAvatar = async () => {
  if (!previewUrl.value) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  try {
    uploading.value = true
    
    // 将Base64转换为文件
    const file = base64ToFile(previewUrl.value, 'avatar.jpg')
    
    // 上传文件
    const response = await uploadAvatar(file)
    
    if (response.code === 200) {
      ElMessage.success('头像上传成功')
      
      // 更新头像数据，优先使用url
      const avatarUrl = response.data?.url || response.data?.filePath
      if (avatarUrl) {
        doctorInfo.value.avatar = avatarUrl
        // 更新本地存储
        localStorage.setItem('doctorInfo', JSON.stringify(doctorInfo.value))
      }
      
      // 清除预览
      previewUrl.value = ''
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请检查网络连接')
  } finally {
    uploading.value = false
  }
}

// 取消上传
const cancelUpload = () => {
  previewUrl.value = ''
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 组件挂载时加载医生信息
onMounted(() => {
  const storedInfo = localStorage.getItem('doctorInfo')
  if (storedInfo) {
    try {
      doctorInfo.value = JSON.parse(storedInfo)
    } catch (error) {
      console.error('解析医生信息失败:', error)
    }
  }
})
</script>

<style scoped>
.avatar-test {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.test-section h3 {
  margin-top: 0;
  color: #303133;
}

.preview-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.preview-actions {
  margin-top: 15px;
}

.preview-actions .el-button {
  margin-right: 10px;
}

.avatar-uploader {
  margin-bottom: 15px;
}
</style>
